#include "VStdAfx.h"
#include "VStaticMeshRender.h"


void VStaticRenderMesh::RT_Init()
{
	RT_InitVertexDeclaration();

	// Create Vertex Buffers;
	if (m_SrcMeshData)
	{
		const VStaticMesh::Surface Surface = m_SrcMeshData->GetSurface(0);

		m_CommonVertexBuffer = VEnv.RI->CreateVertexBuffer(Surface.NumVertics * sizeof(CommonVertex));
		//m_NormalVertexBuffer = VEnv.RI->CreateVertexBuffer(NumVertics * sizeof(NormalVertex));
		CommonVertex* ComonVertics = (CommonVertex*)m_CommonVertexBuffer->Lock(0, Surface.NumVertics * sizeof(CommonVertex));
		//NormalVertex* NormalVertics = (NormalVertex*)m_NormalVertexBuffer->Lock(0, NumVertics * sizeof(NormalVertex));

		for (UINT VertexIndex = 0; VertexIndex < (UINT)Surface.NumVertics; ++VertexIndex)
		{
			const VStaticMesh::Vertex& SrcVertex = Surface.Vertics[VertexIndex];
			ComonVertics->Position = SrcVertex.Position;
			ComonVertics->TexCoord.x = SrcVertex.Texcoord.x;
			ComonVertics->TexCoord.y = SrcVertex.Texcoord.y;
			ComonVertics->Normal = SrcVertex.Normal;
			ComonVertics++;
		}
		m_CommonVertexBuffer->Unlock();

		if (Surface.NumVertics < 65536)
		{
			UINT IndicsSize = Surface.NumIndics * sizeof(WORD);
			m_IndexBuffer = VEnv.RI->CreateIndexBuffer(IndicsSize, FALSE);
			WORD* Indics = (WORD*)m_IndexBuffer->Lock(0, IndicsSize);
			VMemcpy(Indics, Surface.Indices, IndicsSize);
			m_IndexBuffer->Unlock();
		}
	}
}

void VStaticRenderMesh::RT_Shutdown()
{
	m_CommonVertexBuffer = NULL;
	m_TangentVertexBuffer = NULL;
	m_IndexBuffer =NULL;
	m_VertexDeclaration = NULL;
	
	m_DepthVertexDeclaration = NULL;

}

void VStaticRenderMesh::RT_InitVertexDeclaration()
{
	VRVertexElement VertexElements[] = {
		0,	0,	VRVET_FLOAT3, VRVEU_POSITION, 0,
		0,	12,	VRVET_FLOAT2, VRVEU_TEXCOORD, 0,
		0,	20,	VRVET_UBYTE4, VRVEU_NORMAL,	0,
	};
	m_VertexDeclaration = VEnv.RI->CreateVertexDeclaration(VertexElements, sizeof(VertexElements)/sizeof(VRVertexElement));
	m_DepthVertexDeclaration = m_VertexDeclaration;
}

void VStaticRenderMesh::RT_SetDepthStreams(void* MaterialBindInfo)
{
	VEnv.RI->SetVertexBuffer(0, m_CommonVertexBuffer, 0, sizeof(CommonVertex));
}

void VStaticRenderMesh::RT_SetStreams(void* MaterialBindInfo)
{
	VEnv.RI->SetVertexBuffer(0, m_CommonVertexBuffer, 0, sizeof(CommonVertex));
}